package com.alipay.rebate.shop.service.customer.impl;

import com.alipay.rebate.shop.constants.StatusCode;
import com.alipay.rebate.shop.constants.UserIncomeConstant;
import com.alipay.rebate.shop.core.AbstractService;
import com.alipay.rebate.shop.dao.mapper.TaskDoRecordMapper;
import com.alipay.rebate.shop.dao.mapper.TaskSettingsMapper;
import com.alipay.rebate.shop.dao.mapper.UserIncomeMapper;
import com.alipay.rebate.shop.exceptoin.BusinessException;
import com.alipay.rebate.shop.helper.UserIncomeBuilder;
import com.alipay.rebate.shop.model.TaskDoRecord;
import com.alipay.rebate.shop.model.TaskSettings;
import com.alipay.rebate.shop.model.UserIncome;
import com.alipay.rebate.shop.service.customer.CustomerTaskDoRecordService;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * Created by CodeGenerator on 2019/10/17.
 */
@Service
@Transactional
public class CustomerTaskDoRecordServiceImpl extends AbstractService<TaskDoRecord> implements
    CustomerTaskDoRecordService {

    private Logger logger = LoggerFactory.getLogger(CustomerTaskDoRecordServiceImpl.class);
    @Resource
    private TaskDoRecordMapper taskDoRecordMapper;
    @Resource
    private TaskSettingsMapper taskSettingsMapper;
    @Resource
    private UserIncomeMapper userIncomeMapper;

    @Override
    public List<TaskDoRecord> selectNewUserAndDailyTask(Long userId) {
        List<TaskDoRecord> data = taskDoRecordMapper.selectNewUserAndDailyTask(userId);
        logger.debug("data is : {}",data);
        return data;
    }

    @Override
    public void addTaskDoRecord(TaskDoRecord taskDoRecord) {
        TaskSettings taskSettings =
            taskSettingsMapper.selectUseSettingsBySubType(taskDoRecord.getSubType());
        Integer count = taskDoRecordMapper.selectCountBySubType(taskDoRecord.getUserId(),
            taskDoRecord.getSubType());
        logger.debug("count and settings count is : {},{}", count,taskSettings.getMaxTimes());
        if (count!=null && count >= taskSettings.getMaxTimes()){
            throw new BusinessException("每日任务次数已达上限",StatusCode.TASK_TIMES_REACHED);
        }
        taskDoRecordMapper.insertSelective(taskDoRecord);
        UserIncome userIncome = UserIncomeBuilder
            .buildNotOrdersRelateUserIncome(UserIncomeConstant.BROWSE_AWAED_TYPE,
                taskSettings.getAwardType(),Long.valueOf(taskSettings.getAwardNum()),
                taskDoRecord.getUserId());
        userIncomeMapper.insertSelective(userIncome);
    }
}
